import os
import subprocess
import time


def run_server(ip, port):
    # 获取当前脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))

    # **确保路径正确**
    reports_dir = os.path.join(script_dir, "case", 'allure_file', "allure-history")

    # **打印目录路径，检查是否正确**
    print(f"Serving directory: {reports_dir}")

    # **检查目录是否存在**
    if not os.path.exists(reports_dir):
        print(f"Error: Directory {reports_dir} does not exist!")
        return

    # 启动 HTTP 服务器
    process = subprocess.Popen(
        ["python", "-m", "http.server", str(port)],
        cwd=reports_dir,  # 确保这里的目录是你手动能成功启动的路径
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL
    )

    time.sleep(1)  # 等待服务器启动

    print(f"Server running at: http://{ip}:{port}")

    try:
        process.wait()
    except KeyboardInterrupt:
        process.terminate()
        print("Server stopped.")

    return f"http://{ip}:{port}"


if __name__ == "__main__":
    run_server("192.168.1.8", 9999)
    # run_server("192.168.31.107", 9999)
